<template>
    <div class="userContainer">
        <div class="searchRow">
            <div class="inputRow">
                <div class="inputBox">
                    <div class="labelText">歌名：</div>
                    <a-input v-model:value="queryForm.pageModel.query.title0"
                        placeholder="请输入歌名" :allowClear="true"></a-input>
                </div>
            </div>
            <div class="btnBox">
                <a-button type="primary" @click="getTableData()" class="queryBtn">
                    查询
                </a-button>
                <a-button class="resetBtn" @click="reset">重置</a-button>
            </div>
        </div>

        <div class="tableOperation">
            <div class="operationBtn">
                <a-button type="primary" @click="showAddModel" class="queryBtn">
                    添加
                </a-button>
            </div>
            <a-table :columns="tableData.columns" :pagination="pagination" :data-source="tableData.data"
                :loading="tableLoading">
                <template #headerCell="{ column }">
                </template>

                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'cover'">
                        <a-image :width="200" :src="record.cover"></a-image>
                    </template>
                    <template v-if="column.key === 'music'">
                        <audio :src="record.music" controls />
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <a-switch v-model:checked="record.status1" checked-children="启用" un-checked-children="禁用"
                            @change="changeMusicStatus(record)" />
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <span>
                            <a class="actionBtn" @click="handleDeleteUser(record.id)">删除</a>
                            <a-divider type="vertical" />
                            <a class="actionBtn" @click="showEditModel(record)">编辑</a>
                        </span>
                    </template>
                </template>
            </a-table>
        </div>

        <a-modal v-model:open="open1" title="添加歌曲" @ok="handleAddMusic" @cancel="hiddenModel">
            <template #footer>
                <a-button class="cancelBtn" key="back" @click="open1.value = false">取消</a-button>
                <a-button class="confirmBtn" key="submit" type="primary" :loading="loading1"
                    @click="handleAddMusic">确定</a-button>
            </template>

            <a-form ref="formRef" :model="editRecord" :rules="rules">
                <a-form-item label="歌名" name="title">
                    <a-input v-model:value="editRecord.title" />
                </a-form-item>
                <a-form-item label="歌手" name="artist">
                    <a-input v-model:value="editRecord.artist" />
                </a-form-item>
                <a-form-item label="封面" name="coverFileInfoId">
                    <a-upload v-model:file-list="fileList" list-type="picture-card" @preview="handlePreview"
                        :customRequest="customRequest" @remove="handleRemove">
                        <div v-if="fileList.length < 1">
                            <plus-outlined />
                            <div style="margin-top: 8px">上传</div>
                        </div>
                    </a-upload>
                    <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
                        <img style="width: 100%" :src="previewImage" />
                    </a-modal>
                </a-form-item>
                <a-form-item label="音频" name="musicFileInfoId">
                    <a-upload v-model:file-list="fileList1" name="file" :customRequest="customRequest1"
                        :before-upload="beforeUpload1">
                        <a-button>
                            <upload-outlined></upload-outlined>
                            上传歌曲
                        </a-button>
                    </a-upload>
                </a-form-item>
                <a-form-item label="状态" name="status">
                    <a-switch v-model:checked="editRecord.status1" checked-children="启用" un-checked-children="禁用" />
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal v-model:open="open2" title="编辑歌曲" @ok="handleEditMusic" @cancel="hiddenModel">
            <template #footer>
                <a-button class="cancelBtn" key="back" @click="cancelUpdateModel()">取消</a-button>
                <a-button class="confirmBtn" key="submit" type="primary" :loading="loading1"
                    @click="handleEditMusic">确定</a-button>
            </template>

            <a-form ref="formRef" :model="editRecord" :rules="rules">
                <a-form-item label="歌名" name="title">
                    <a-input v-model:value="editRecord.title" />
                </a-form-item>
                <a-form-item label="歌手" name="artist">
                    <a-input v-model:value="editRecord.artist" />
                </a-form-item>
                <a-form-item label="封面" name="coverFileInfoId">
                    <a-upload v-model:file-list="fileList" list-type="picture-card" @preview="handlePreview"
                        :customRequest="customRequest" @remove="handleRemove">
                        <div v-if="fileList.length < 1">
                            <plus-outlined />
                            <div style="margin-top: 8px">上传</div>
                        </div>
                    </a-upload>
                    <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
                        <img style="width: 100%" :src="previewImage" />
                    </a-modal>
                </a-form-item>
                <a-form-item label="音频" name="musicFileInfoId">
                    <a-upload v-model:file-list="fileList1" name="file" :customRequest="customRequest1"
                        :before-upload="beforeUpload1">
                        <a-button>
                            <upload-outlined></upload-outlined>
                            上传歌曲
                        </a-button>
                    </a-upload>
                </a-form-item>
                <a-form-item label="状态" name="status">
                    <a-switch v-model:checked="editRecord.status1" checked-children="启用" un-checked-children="禁用" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { deleteUser, findUserPage } from '@/api/user';
import { upload1 } from '@/api/file';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { findMusicPage, addMusic, updateMusic } from '@/api/musicPlayer';
import { allowTypes, allowedTypeNames, maxSize } from '@/utils/common'

const tableLoading = ref(false);
const moduleId = '2';
const fileList = ref([]);
const fileList1 = ref([]);
// 预览
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
// 新增弹框
const open1 = ref(false);
// 编辑弹框
const open2 = ref(false);
// 国际化
const globalI18n = useI18n();
// 编辑/新增用户弹框
const loading1 = ref(false);
// 编辑/新 用户参数
const editRecord = reactive({
    moduleId: moduleId,
    id: null,
    status: 1,
    status1: true,
    title: '',
    artist: '',
    coverFileInfoId: '',
    musicFileInfoId: '',
});

const tableData = reactive({
    columns: computed(() => [
        {
            title: '序号',
            dataIndex: 'no',
            key: 'no',
            width: 60,
            customRender: ({ index }) => (pagination.current - 1) * pagination.pageSize + index + 1,
        },
        {
            title: '歌名',
            dataIndex: 'title',
            key: 'title',
            maxWidth: 150,
        },
        {
            title: '歌手',
            dataIndex: 'artist',
            key: 'artist',
            maxWidth: 150,
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            maxWidth: 200,
        },
        {
            title: '音频',
            key: 'music',
            dataIndex: 'music',
            maxWidth: 80,
        },
        {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            maxWidth: 90,
        },
        {
            title: '创建人',
            key: 'createNickName',
            dataIndex: 'createNickName',
            maxWidth: 80,
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
            maxWidth: 90,
        },
        {
            title: '更新人',
            key: 'updateNickName',
            dataIndex: 'updateNickName',
            maxWidth: 80,
        },
        {
            title: '更新时间',
            key: 'updateTime',
            dataIndex: 'updateTime',
            maxWidth: 90,
        },
        {
            title: '操作',
            key: 'action',
        },
    ]),
    data: [],
});

// 查询对象
const queryForm = reactive({
    pageModel: {
        pageNow: 1,
        pageSize: 10,
        query: {
          title0: '',
        },
        sort: ['1create_time']
    }
});
const isReturnFirstPage = ref(true);
// 定义响应式的分页对象
const pagination = reactive({
    class: 'myPagination',
    total: 0, // 总条数
    current: 1, // 当前页数
    pageSize: 10, // 每页显示的条数
    // pageSizeOptions: ['10', '20', '30', '40', '50'],
    showSizeChanger: true, // 是否可以改变每页显示的条数
    showQuickJumper: true, // 是否可以快速跳转到指定页
    showTotal: (total) => `共 ${total} 条`, // 显示总条数和当前数据范围
    onShowSizeChange: (current, pageSize) => handleShowSizeChange(current, pageSize), // 改变每页数量时更新显示
    onChange: (page, pageSize) => handleShowPageChange(page, pageSize) // 页码改变时的回调函数
});
const formRef = ref(null);
const rules = {
    title: [
        {
            required: true,
            message: '请输入歌名',
            trigger: 'change',
        },
    ],
    artist: [
        {
            required: true,
            message: '请输入歌手',
            trigger: 'change',
        },
    ],
    musicFileInfoId: [
        {
            required: true,
            message: '请上传音频',
            trigger: 'change',
        },
    ],
    coverFileInfoId: [
        {
            required: true,
            message: '请上传封面',
            trigger: 'change',
        },
    ],
};

// 处理每页显示条数改变的函数
const handleShowSizeChange = (current, pageSize) => {
    console.log(current, pageSize);
    pagination.pageSize = pageSize;
};

// 处理页码改变的函数
const handleShowPageChange = (page, pageSize) => {
    console.log('handleShowPageChange.', page, pageSize, isReturnFirstPage.value);
    expandedRowKeys.value = [];
    if (isReturnFirstPage.value) {
        pagination.current = 1;
        isReturnFirstPage.value = false;
    } else {
        pagination.current = page;
    }
};

// 预览图片
const handlePreview = async file => {
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

const reset = () => {
    queryForm.pageModel.query.title0 = '';
    getTableData();
}

const getTableData = () => {
    tableLoading.value = true;
    queryForm.pageModel.pageSize = pagination.pageSize;
    queryForm.pageModel.pageNow = pagination.current;
    findMusicPage(queryForm).then((res) => {
        if (res.code === 200) {
            console.log(res.data);
            tableData.data = res.data.list.dataList;
            tableLoading.value = false;
        }
    }).catch((err) => {
    });
}
// 展示编辑框
const showEditModel = (record) => {
    editRecord.id = record.id;
    editRecord.title = record.title;
    editRecord.artist = record.artist;
    editRecord.status = record.status;
    editRecord.coverFileInfoId = record.coverFileInfoId;
    editRecord.musicFileInfoId = record.musicFileInfoId;
    editRecord.status1 = record.status1;
    fileList.value = [
        {
            uid: '-1',
            name: record.title,
            status: 'done',
            url: record.cover,
        },
    ];
    fileList1.value = [
        {
            uid: '-2',
            name: record.title,
            status: 'done',
            url: record.music,
        },
    ];

    open2.value = true;
}
// 删除音乐
const handleDeleteUser = (id) => {
    Modal.confirm({
        title: globalI18n.t('tips.deleteConfirm'),
        icon: h(ExclamationCircleOutlined),
        content: '',
        okText: `${globalI18n.t('common.confirm')}`,
        okType: 'danger',
        cancelText: `${globalI18n.t('common.cancel')}`,
        onOk() {
            deleteUser(id).then((res) => {
                if (res.code === 200) {
                    getTableData();
                    message.success(globalI18n.t('tips.deleteSuccess'));
                }
            });
        },
        onCancel() {
            console.log('Cancel');
        },
    });
}

const showAddModel = () => {
    open1.value = true;
}
// 重置添加表单
const resetAddEditForm = () => {
    editRecord.title = '';
    editRecord.artist = '';
    editRecord.coverFileInfoId = '';
    editRecord.musicFileInfoId = '';
    editRecord.status = false;
    fileList.value = [];
    fileList1.value = [];
}

// 添加音乐
const handleAddMusic = () => {
    formRef.value
        .validate()
        .then(() => {
            editRecord.status = editRecord.status1 ? 1 : 0;
            addMusic(editRecord).then(res => {
                if (res.code === 200 && res.data) {
                    console.log(res);
                    message.success('添加成功');
                    open1.value = false;
                    resetAddEditForm();
                    getTableData();
                }
            }).catch(err => {
                console.log(err);
            });
        })
        .catch(error => {
            console.log(error);
        });
}

// 编辑音乐
const handleEditMusic = () => {
    formRef.value
        .validate()
        .then(() => {
            editRecord.status = editRecord.status1 ? 1 : 0;
            updateMusic(editRecord).then(res => {
                if (res.code === 200 && res.data) {
                    console.log(res);
                    message.success('编辑成功');
                    open2.value = false;
                    resetAddEditForm();
                    getTableData();
                }
            }).catch(err => {
                console.log(err);
            });
        })
        .catch(error => {
            console.log(error);
        });
}

// 取消预览
const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
};

const cancelUpdateModel = () => {
    open2.value = false;
    resetAddEditForm();
};

// 上传封面
const customRequest = async ({ file }) => {
    if (fileList.value.length > 1) {
        message.warn(`最多只能上传1张图片`);
        return;
    }
    // 校验图片大小
    if (file.size > maxSize) {
        const sizeInMB = (maxSize / (1024 * 1024)).toFixed(1);
        message.warn(`图片大小不能超过${sizeInMB}MB`);
        return;
    }
    // 校验图片类型
    if (!allowTypes.includes(file.type)) {
        const allowedTypesText = allowTypes.map(type => allowedTypeNames[type] || type).join('、');
        message.warn(`请上传${allowedTypesText}格式的图片`);
        return; // 阻止上传
    }
    // 上传文件
    const formData = new FormData();
    formData.append('file', file);
    formData.append('moduleId', moduleId);
    upload1(formData).then(res => {
        const fileInfo = res.data.data;
        if (res.data.code !== 200 || !fileInfo) {
            message.success("上传失败");
        } else {
            message.success("上传成功");
            file.url = fileInfo.fileAddress;
            file.id = fileInfo.id;
            let newFileList = [];
            for (let i = 0; i < fileList.value.length; i++) {
                let one = fileList.value[i];
                if (!one.originFileObj) {
                    newFileList.push(one)
                }
            }
            newFileList.push(file);
            fileList.value = [...newFileList];
            editRecord.coverFileInfoId = fileInfo.id;
        }
    }).catch(err => {
        console.log(err);
    });
};

const beforeUpload1 = () => {
    if (fileList1.value.length >= 1) {
        message.warn(`最多只能上传1个音频`);
        fileList1.value = fileList1.value[0];
        return false;
    }
    return true;
}

// 上传音频
const customRequest1 = async ({ file }) => {
    // 上传文件
    const formData = new FormData();
    formData.append('file', file);
    formData.append('moduleId', moduleId);
    upload1(formData).then(res => {
        const fileInfo = res.data.data;
        if (res.data.code !== 200 || !fileInfo) {
            message.success("上传失败");
        } else {
            message.success("上传成功");
            file.url = fileInfo.fileAddress;
            file.id = fileInfo.id;
            let newFileList = [];
            for (let i = 0; i < fileList1.value.length; i++) {
                let one = fileList1.value[i];
                if (!one.originFileObj) {
                    newFileList.push(one)
                }
            }
            newFileList.push(file);
            fileList1.value = [...newFileList];
            editRecord.musicFileInfoId = fileInfo.id;
        }
    }).catch(err => {
        console.log(err);
    });
};
// 更新音乐启用状态
const changeMusicStatus = (record) => {
    record.status = record.status1 ? 1 : 0;
    updateMusic(record).then(res => {
        if (res.code === 200) {
            if (record.status1) {
                message.success('启用成功！');
            } else {
                message.info('禁用成功！');
            }
        }
    }).catch(err => {
        console.log(err);
    });
}

const hiddenModel = () => {
    open1.value = false;
    open2.value = false;
    resetAddEditForm();
}

onMounted(() => {
    getTableData();
});

</script>

<style scoped lang="scss">
.userContainer {

    .searchRow {
        display: flex;
        background-color: #fff;
        padding: 20px;
        justify-content: space-between;
        margin-top: 20px;
        margin-bottom: 20px;
        flex-wrap: wrap;

        .inputRow {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .inputBox {
                display: flex;
                align-items: center;
                margin-right: 70px;
                margin-top: 10px;
                margin-bottom: 10px;

                .labelText {
                    white-space: nowrap;
                    font-size: 14px;
                }

                .selectClass {
                    width: 199px;
                }
            }
        }

        .btnBox {
            display: flex;
            flex-wrap: nowrap;

            button {
                margin: 10px 0 10px 9px;
            }

            .ant-btn:first-child {
                margin-right: 8px !important;
            }
        }
    }

    .tableOperation {
        min-width: 600px;
        overflow: auto;
        .custom-table {
            padding: 10px;
        }

        background-color: #fff;

        .operationBtn {
            display: flex;
            justify-content: right;
            margin-bottom: 20px;
        }

        padding: 20px;
    }

    .actionBtn {
        color: #4ab44a;

        &:hover {
            color: #388b38;
        }
    }
}
</style>